﻿'This file is part of WSUS Helper <http://wsushelper.codeplex.com/>.

'WSUS Helper is free software: you can redistribute it and/or modify
'it under the terms of the GNU General Public License as published by
'the Free Software Foundation, either version 2 of the License, or
'(at your option) any later version.

'WSUS Helper is distributed in the hope that it will be useful,
'but WITHOUT ANY WARRANTY; without even the implied warranty of
'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'GNU General Public License for more details.

'You should have received a copy of the GNU General Public License
'along with WSUS Helper.  If not, see <http://www.gnu.org/licenses/>.

Imports System.Text

Module FileOutput

    ''' <summary>
    ''' Export the contents of a DataGridView to a CSV text file.
    ''' </summary>
    ''' <param name="TableToSave">Table to export.</param>
    ''' <param name="FileName">Filename to export the data to.</param>
    ''' <param name="ResultText">Variable to store the result message.</param>
    ''' <returns>Success status.</returns>
    ''' <remarks></remarks>
    Public Function SaveTableToCSV(ByRef TableToSave As DataGridView, ByVal FileName As String, ByRef ResultText As String) As Boolean

        Dim oLine As StringBuilder
        Dim iStartCol As Integer
        Dim iScan As Integer
        Dim bResult As Boolean = False

        'Check there are visible data rows to export
        Dim iVisibleRows As Integer = TableToSave.Rows.Count
        Dim iStartRow As Integer = 0
        If iVisibleRows > 0 Then
            If TableToSave.Rows(0).Visible = False Then
                iVisibleRows -= 1
                iStartRow = 1
            End If
        End If

        'Start at column index 1 (not 0) if the first column (of the first visible row) is hidden.
        If TableToSave.Rows(iStartRow).Cells(0).Visible = True Then
            iStartCol = 0
        Else
            'Check if there are visible columns too
            If TableToSave.Rows(iStartRow).Cells.Count > 0 Then
                iStartCol = 1
            Else
                iStartCol = -1
            End If
        End If


        'Only do this if there is actually some data to export
        If (iVisibleRows > 0) And (iStartCol > -1) Then
            Try
                'Try to create a new output file.
                Dim oCSV As New IO.StreamWriter(FileName)

                Try
                    'Initialise the line builder
                    oLine = New StringBuilder

                    iScan = iStartCol
                    'Build header row
                    While iScan < TableToSave.Columns.Count
                        oLine.Append("""" & TableToSave.Columns(iScan).HeaderText.Replace("""", """""") & """")
                        iScan += 1
                        If iScan < TableToSave.Columns.Count Then
                            oLine.Append(",")
                        End If
                    End While

                    oCSV.WriteLine(oLine.ToString)

                    'Now build and write all the data rows
                    For Each oRow As DataGridViewRow In TableToSave.Rows

                        'Only output displayed rows
                        If oRow.Cells(iStartCol).Visible = True Then
                            'Initialise the line builder
                            oLine = New StringBuilder

                            iScan = iStartCol
                            'Build data row
                            While iScan < oRow.Cells.Count
                                'Escape text with double quotes
                                oLine.Append("""" & oRow.Cells(iScan).Value.ToString.Replace("""", """""") & """")
                                iScan += 1
                                If iScan < oRow.Cells.Count Then
                                    oLine.Append(",")
                                End If
                            End While

                            oCSV.WriteLine(oLine.ToString)

                        End If
                    Next

                    'Success
                    ResultText = "Saved to " & FileName
                    bResult = True

                Catch ex As Exception
                    'Report any file save errors
                    ResultText = "Problem while saving to file " & FileName & ": " & ex.Message
                    bResult = False
                Finally
                    oCSV.Close()
                End Try

            Catch ex As Exception
                'Report any file save errors
                ResultText = "Unable to save to file " & FileName & ": " & ex.Message
                bResult = False
            End Try
        Else
            ResultText = "No row data to save."
            bResult = False
        End If

        Return bResult

    End Function

End Module
